import tagProcess from "./tagProcess.json";

const process = () => {
  let process = {};
  for (let i = 0; i < tagProcess.length; i++) {
    process[tagProcess[i].TAG] = {
      NN: tagProcess[i].NN,
      NNWJ: tagProcess[i].NNWJ,
      SS: tagProcess[i].SS,
      SSWJ: tagProcess[i].SSWJ,
      NS: tagProcess[i].NS,
      NSWJ: tagProcess[i].NSWJ,
      SN: tagProcess[i].SN,
      SNWJ: tagProcess[i].SNWJ,
    };
  }
  // console.log("function: matchSectorsProcess", process);
  return process;
};

const matchSectors = (data, scheme = "NN") => {
  let pro = process();
  let output = new Array();
  for (let i = 0; i < data.length; i++) {
    let tag = data[i].tag;
    let value = data[i].val;
    if (pro[tag] && pro[tag][scheme]) {
      let sectors = new Array();
      let tmp = pro[tag][scheme].split(";");
      tmp.forEach((t, i) => {
        if (t != "") {
          let tmpa = t.split(",");
          sectors.push({ code: tmpa[0], ratio: tmpa[1] });
        }
      });
      output.push({ value, sectors });
    }
  }
  /*
  [
    {
      value:10,
      sectors: [{code:AP01, ratio:1},...]
    },
    ...
  ]
  */
  return output;
};

const matchSeat = (data, scheme) => {
  // each seat
  let output = new Array();
  for (let i = 0; i < scheme.length; i++) {
    let sectors = scheme[i].sectorCodes;
    if (sectors.length == 0) continue;
    let seat = scheme[i].seatName;
    let value = 0;
    let load = 0;
    data.forEach((cell) => {
      let cellValue = 0;
      let cellRatio = 0;
      cell.sectors.forEach((cellSector) => {
        if (sectors.includes(cellSector.code)) {
          cellValue = cell.value;
          if (cellRatio < cellSector.ratio) {
            cellRatio = cellSector.ratio;
          }
        }
      });
      if (cellValue > 0) {
        value += cellValue;
        load += cellValue * cellRatio;
      }
    });
    load = Math.round(load);
    output.push({ seat, value, load, sector: sectors });
  }
  return output;
};

export default function (taggedCell, directionScheme, sectorScheme) {
  let verbose = false;
  if (verbose)
    console.log("function: arrangeSectorData", {
      taggedCell,
      directionScheme,
      sectorScheme,
    });
  if (!taggedCell || !sectorScheme) return null;
  let sectorData = matchSectors(taggedCell, directionScheme);
  let seatData = matchSeat(sectorData, sectorScheme);
  if (verbose)
    console.log("function: arrangeSectorDataResult", {
      sectorData,
      seatData,
    });
  return seatData;
}
